package com.qzxl.conntext.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qzxl.conntext.producer.AccessProducer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AccessListener {

    private static final Logger logger = LoggerFactory.getLogger(AccessListener.class);

    public static Map<String,String> deviceName = new ConcurrentHashMap<>(); // deviceName+deviceId

    @KafkaListener(topicPattern = "sys.PLCEmpiricalData.subdevice.register.response")
    public void equipmentRegisterResponse(ConsumerRecord<Object,Object> record){
        logger.info("注册返回收到时间！！！！！！！！！！！！"+System.currentTimeMillis());
        logger.info("------------------------------------收到的消息是"+record.toString());
        JSONObject registerResponse = (JSONObject) JSON.parse(record.value().toString());
        String id = registerResponse.get("id").toString();
        if(AccessProducer.idMap.containsKey(id)){
            JSONObject response = (JSONObject) JSON.parse(registerResponse.get("response").toString());
            String status = response.get("status").toString();
            if(status.equals("success")){
                String deviceId = registerResponse.getString("deviceId");
                String name = AccessProducer.idMap.get(id);
                deviceName.put(name,deviceId);
            }else {
                logger.error("注册失败，可能已经被注册过");
                logger.info(record.toString());
            }
        }
    }
}
